package com.op.teachingliteapp.fragment.smartpan;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.example.android_file_manger.MainActivity;
import com.op.teachingliteapp.R;
import com.op.teachingliteapp.bean.FileBean;
import com.op.teachingliteapp.common.BaseApp;
import com.op.teachingliteapp.common.Common;
import com.op.teachingliteapp.common.api.ApiConstant;
import com.op.teachingliteapp.common.api.smartpan.CmdForm;
import com.op.teachingliteapp.common.api.smartpan.EntityBean;
import com.op.teachingliteapp.util.DirUtils;
import com.op.teachingliteapp.util.FileUtils;
import com.op.teachingliteapp.util.SharedPreferenceUtil;
import com.op.teachingliteapp.util.ToastUtils;
import com.op.teachingliteapp.util.asynctask.HttpPostTask;
import com.op.teachingliteapp.util.asynctask.OnTaskProcessListener;

public class SmartPanFragment extends Fragment {
	private Button mySmartPan, courseSmartPan, back;
	private ImageButton synchronous, createNewfile;
	private ListView mySmartPanFile;
	private LayoutInflater InflaterDialog;
	public static Boolean smartPantStart;
	private List<FileBean> fileBean;
	private String path, getUserId;
	private CheckBox allChoose;
	private SmartPanListviewAdapter adapter;
	public static EditText mySmartPanFileChoose;
	private boolean isAutoLogin;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		smartPantStart = true;

		InflaterDialog = inflater;
		// 该Fragment的布局
		View root = inflater.inflate(R.layout.fragment_smart_pan, container, false);
		mySmartPanFile = (ListView) root.findViewById(R.id.my_smart_pan_file);
		mySmartPan = (Button) root.findViewById(R.id.my_smart_pan);
		courseSmartPan = (Button) root.findViewById(R.id.course_smart_pan);
		synchronous = (ImageButton) root.findViewById(R.id.synchronous);
		createNewfile = (ImageButton) root.findViewById(R.id.create_newfile);
		allChoose = (CheckBox) root.findViewById(R.id.smart_pan_file_allchoose);
		// 设置云盘按钮图片
		courseSmartPan.setBackgroundResource(R.drawable.course_smart_pan);
		mySmartPan.setBackgroundResource(R.drawable.my_smart_pan_click);
		back = (Button) root.findViewById(R.id.back);
		ImageButton mySmartPanFilePush = (ImageButton) root.findViewById(R.id.my_smart_pan_file_push);
		// 本地路径
		// 获取用户Id
		SharedPreferences preferences = getActivity().getSharedPreferences("TeachingLite", Context.MODE_PRIVATE);
		// 暂时使用userNumber测试
		getUserId = preferences.getString(Common.Prefs.USER_ID, "");
		path = Common.rootFilePath.ROOT_FILE_PATH + getUserId;
		adapter = getAdapter(path);
		// 设置listview的adapter
		mySmartPanFile.setAdapter(adapter);
		// item监听
		mySmartPanFile.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// 如果点击的是文件夹 则进入
				if (!adapter.isFile(position)) {
					path += "/" + adapter.getFileName(position);
					localRefreshList(path);
				}
			}
		});
		/**
		 * 全选按钮监听
		 */
		allChoose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				Map<String, Object> prefsMap = new HashMap<String, Object>();
				if (isChecked) {
					prefsMap.put(Common.Prefs.DROP_DOWN_BUTTON_CONDITION, true);
					SharedPreferenceUtil.saveData(getActivity(), prefsMap);
					localRefreshList(path);
				} else {
					prefsMap.put(Common.Prefs.DROP_DOWN_BUTTON_CONDITION, false);
					SharedPreferenceUtil.saveData(getActivity(), prefsMap);
					localRefreshList(path);
				}
			}
		});

		/**
		 * 上传按钮监听
		 */
		mySmartPanFilePush.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// 上传文件的dialog的布局以及控件
				final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();

				alertDialog.show();
				Window window = alertDialog.getWindow();
				window.setContentView(R.layout.my_smart_pan_dialog);
				mySmartPanFileChoose = (EditText) window.findViewById(R.id.my_smart_pan_file_path);
				Button mySmartPanDialogFilePush = (Button) window.findViewById(R.id.my_smart_pan_file_push);
				Button SmartPanPushDetermine = (Button) window.findViewById(R.id.push_file_determine);
				Button SmartPanPushCancel = (Button) window.findViewById(R.id.push_file_cancel);
				// dialog的上传按钮监听
				mySmartPanDialogFilePush.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						pushFileAndGetFilePath();
					}
				});
				// 选择要添加的文件的按钮监听
				mySmartPanFileChoose.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						pushFileAndGetFilePath();
					}

				});
				// 确定按钮监听
				SmartPanPushDetermine.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						String path = mySmartPanFileChoose.getText().toString();
						File file = new File(path);
						if (!file.isFile()) {
							ToastUtils.show(getActivity(), "请选择文件");
						} else {
							ToastUtils.show(getActivity(), file.getName());
						}

					}
				});
				// 取消按钮监听
				SmartPanPushCancel.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						alertDialog.dismiss();
					}
				});
			}
		});
		/**
		 * 新建文件夹按钮监听
		 */
		createNewfile.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
				alertDialog.show();
				Window window = alertDialog.getWindow();
				window.setContentView(R.layout.create_folder_dialog);
				// 实例化按钮和文件输入地址
				TextView createFolderTitle = (TextView) window.findViewById(R.id.create_folder_dialog_title);
				createFolderTitle.setText("新建文件夹");
				final EditText createFolderPath = (EditText) window.findViewById(R.id.create_folder_dialog_path);
				Button createFolderDetermine = (Button) window.findViewById(R.id.create_folder_determine);
				Button createFolderCancel = (Button) window.findViewById(R.id.create_folder_cancel);
				// 取消按钮监听
				createFolderCancel.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						alertDialog.dismiss();
					}
				});
				// 确定按钮监听
				createFolderDetermine.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						final String fileName = createFolderPath.getText().toString();
						final String ownerId = SharedPreferenceUtil.getInstance(getActivity()).getString(Common.Prefs.USER_ID, "");

						// path后如果没有"/",记得加"/"
						String cmdJson = CmdForm.generateJsonCmd(ownerId, localConversionSend(path), CmdForm.CMD_CREATE_FOLDER, fileName);
						Log.i("-----", "xxxxxxxxxxxxxxxxxx" + localConversionSend(path));
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("CMD", cmdJson));
						HttpPostTask task = new HttpPostTask(getActivity(), ApiConstant.SMART_PAN_URL, params);
						task.setTaskListener(new OnTaskProcessListener() {
							@Override
							public void prepare() {
							}

							@Override
							public void completed(String result) {

								Log.i("-----", result);
								String msg = CmdForm.getOutputMessage(result);
								if (msg.equals("create folder sucess")) {
									Log.i("-----", localConversionSend(path) + "/" + fileName + "/");
									boolean isSuccess = FileUtils.makeDirs(Common.rootFilePath.ROOT_FILE_PATH + ownerId + "/" + localConversionSend(path) + "/" + fileName + "/");
									if (isSuccess) {
										ToastUtils.show(getActivity(), "文件夹创建成功");
										fileBean = new DirUtils(getActivity(), getUserId).getFileList(Common.rootFilePath.ROOT_FILE_PATH + ownerId + "/" + localConversionSend(path));
										adapter.setList(fileBean);
										adapter.notifyDataSetChanged();
									} else {
										ToastUtils.show(getActivity(), "文件夹创建失败");
									}
									localRefreshList(path);
								} else {
									ToastUtils.show(getActivity(), "文件夹创建失败");
								}
								alertDialog.dismiss();
							}

						});
						task.execute();

					}
				});

			}
		});
		/**
		 * 我的云盘按钮监听
		 */
		mySmartPan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				courseSmartPan.setBackgroundResource(R.drawable.course_smart_pan);
				mySmartPan.setBackgroundResource(R.drawable.my_smart_pan_click);
				path = Common.rootFilePath.ROOT_FILE_PATH + getUserId;
				localRefreshList(path);
			}
		});
		/**
		 * 课程云盘按钮监听
		 */
		courseSmartPan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				path = Common.rootFilePath.ROOT_FILE_PATH + getUserId + "/Course";
				localRefreshList(path);
				courseSmartPan.setBackgroundResource(R.drawable.course_smart_pan_click);
				mySmartPan.setBackgroundResource(R.drawable.my_smart_pan);
			}
		});
		/**
		 * 同步按钮监听
		 */
		synchronous.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				fileBean = new DirUtils(getActivity(), getUserId).getFileList(path);

				String cmdJson = CmdForm.generateJsonCmd(getUserId, localConversionSend(path), CmdForm.CMD_LIST);
				Log.i("xxxxxxxxxxxxxxxxxx", "" + path);
				// 发送POST请求给ApiConstant.SMART_PAN_URL
				getPostResult(cmdJson);
			}
		});
		/**
		 * 返回上一级按钮监听
		 */
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				backClicked(v);
			}
		});
		new DirUtils(getActivity(), "123").getFilesNameByDir("Course");
		return root;
	}

	@Override
	public void onPause() {
		smartPantStart = false;
		super.onPause();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	public void backClicked(View v) {
		// 获取上一级地址
		int backwhere = path.lastIndexOf("/");
		if (path.equals(Common.rootFilePath.ROOT_FILE_PATH + getUserId)) {

		} else {
			path = path.substring(0, backwhere);
			Log.i("SmartPanFragment", "上一级路径：" + path);
			Log.i("SmartPanFragment", "上一级路径长度：" + backwhere);
		}
		localRefreshList(path);
	}

	/**
	 * 获取文件的fileBean
	 */
	public SmartPanListviewAdapter getAdapter(String path) {
		Log.i("getadapter", "getadapter");
		fileBean = new DirUtils(getActivity(), getUserId).getFileList(path);
		// 判断是不是空文件夹
		if (fileBean != null && !fileBean.isEmpty()) {
			adapter = new SmartPanListviewAdapter(getActivity(), fileBean);
		} else {
			fileBean = new ArrayList<FileBean>();
			adapter = new SmartPanListviewAdapter(getActivity(), fileBean);
		}
		return adapter;
	}

	/**
	 * 上传选定文件获得文件路径
	 */

	public void pushFileAndGetFilePath() {
		Intent intent;
		intent = new Intent(getActivity(), MainActivity.class);
		startActivity(intent);

	}

	public void getPostResult(String cmdJson) {
		// 做异步请求
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("CMD", cmdJson));
		HttpPostTask task = new HttpPostTask(getActivity(), ApiConstant.SMART_PAN_URL, params);
		task.setTaskListener(new OnTaskProcessListener() {
			@Override
			public void prepare() {
			}

			@Override
			public void completed(String result) {
				Log.i("SmartPanFragment", "同步返回数据: " + result);

				List<EntityBean> entityBeanList = new ArrayList<EntityBean>();
				if (CmdForm.fillEntityBeanList(entityBeanList, result)) {
					System.out.println("获取到的Size为: " + entityBeanList.size());
				} else {
					System.out.println("路径有问题");
				}

				// 本地数据库与云盘对比
				for (int i = 0; i < fileBean.size(); i++) {
					for (int j = 0; j < entityBeanList.size(); j++) {
						if (fileBean.get(i).getName().equals(entityBeanList.get(j).getEntityName())) {
							fileBean.get(i).setCondition("HAVA");
							Log.i("SmartPanFragment", "云盘:" + entityBeanList.get(j).getEntityName() + "本地:" + fileBean.get(i).getName());
						}
					}
					Log.i("SmartPanFragment", fileBean.get(i).getName() + ":" + fileBean.get(i).getCondition());
					// 如果不等，则说明本地Bean内包含网络上不存在的Bean
					if (fileBean.get(i).getCondition() == null || !fileBean.get(i).getCondition().equals("HAVA")) {
						fileBean.get(i).setCondition("SmartNO");
					}
				}
				// 云盘与本地对比
				for (int i = 0; i < entityBeanList.size(); i++) {
					for (int j = 0; j < fileBean.size(); j++) {
						if (entityBeanList.get(i).getEntityName().equals(fileBean.get(j).getName())) {
							entityBeanList.get(i).setCondition("HAVA");
						}
					}
					// 如果不等，则说明云盘内包含本地不存在的Bean
					if (entityBeanList.get(i).getCondition() == null || !entityBeanList.get(i).getCondition().equals("HAVA")) {
						boolean isFile;
						FileBean addFileBean = new FileBean();
						addFileBean.setCondition("ThisNO");
						addFileBean.setName(entityBeanList.get(i).entityName);
						addFileBean.setSize(entityBeanList.get(i).getFileSize());
						addFileBean.setPath(fileBean.get(fileBean.size() - 1).getPath());
						// 判断是否是文件
						if (entityBeanList.get(i).getEntityType().equals(EntityBean.TYPE_FILE)) {
							isFile = true;

						} else {
							isFile = false;
							Log.i("SmartPanFragment", "" + addFileBean.getName());
							createFolders(addFileBean);
						}
						addFileBean.setFile(isFile);

						fileBean.add(addFileBean);
						adapter.setList(fileBean);
						adapter.notifyDataSetChanged();
					}
				}
			}

		});
		task.execute();
	}

	/**
	 * 创建 相应课程的文件夹
	 * 
	 * @param userId
	 * @param list
	 */
	public void createFolders(FileBean fileBean) {
		SharedPreferences preferences = SharedPreferenceUtil.getInstance(BaseApp.getAppContext());
		String currentUserId = preferences.getString(Common.Prefs.USER_ID, "");
		DirUtils dirUtils = new DirUtils(getActivity(), currentUserId);
		List<String> courses = new ArrayList<String>();
		courses.add(fileBean.getName());
		// Log.i("SmartPan", "" + fileBean.getPath().substring(0,
		// fileBean.getPath().lastIndexOf("/")));
		dirUtils.createDirs(courses, fileBean.getPath().substring(0, fileBean.getPath().lastIndexOf("/")));
	}

	/**
	 * 列表adapter刷新
	 */
	public void localRefreshList(String path) {
		adapter = getAdapter(path);
		adapter.notifyDataSetChanged();
		mySmartPanFile.setAdapter(adapter);

	}

	/**
	 * 本地地址转发送地址
	 */
	public String localConversionSend(String path) {
		String ownerId = SharedPreferenceUtil.getInstance(getActivity()).getString(Common.Prefs.USER_ID, "");
		String pathHeader = Common.rootFilePath.ROOT_FILE_PATH + ownerId;
		String mySmartPanPath = path.replace(pathHeader, "");
		if (mySmartPanPath.equals("")) {
			mySmartPanPath = "/";
		}
		return mySmartPanPath;
	}
}
